package cn.tedu.hotel.serve.security;

import cn.tedu.hotel.serve.mapper.UserMapper;
import cn.tedu.hotel.serve.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法，参数：{}", s);
        UserLoginInfoVO userInfo = userMapper.getUserInfoByUsername(s);
        log.debug("从数据库中根据用户名【{}】查询登录信息，结果：{}", s, userInfo);
        if (userInfo==null){
            return null;
        }
        List<GrantedAuthority> authorities=new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(userInfo.getPermission()));

        UserForDetails userForDetails=new UserForDetails(
              userInfo.getId(),
              userInfo.getNickname(),
              userInfo.getUsername(),
              userInfo.getPassword(),
              userInfo.getEnable()==1,
              authorities
        );
        log.debug("即将向Spring Security返回UserDetails类型的对象：{}", userForDetails);
        return userForDetails;
    }
}
